package controller;

import dao.ContatoDAO;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Contato;

@WebServlet(name = "controleCrud", urlPatterns = {"/crud"})
public class CrudController extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processaRequisicao(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processaRequisicao(request, response);
    }

    protected void processaRequisicao(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try {
            int id;
            String method = request.getParameter("method");
            String nome = request.getParameter("nome");
            String email = request.getParameter("email");
            String endereco = request.getParameter("endereco");

            Contato contato = new Contato();
            ContatoDAO dao = new ContatoDAO();

            contato.setNome(nome);
            contato.setEmail(email);
            contato.setEndereco(endereco);

            if ("save".equals(method)) {
                dao.adiciona(contato);
            } else if ("edit".equals(method)) {
                id = Integer.parseInt(request.getParameter("id"));
                contato.setId(id);
                dao.alterar(contato);
            } else {
                id = Integer.parseInt(request.getParameter("id"));
                dao.delete(id);
            }

            response.sendRedirect("contatos.jsp");

        } catch (Exception e) {

            System.out.println(e);

        }
    }
}
